package com.kma.summer2012.facade;

import com.kma.summer2012.factory.DAOFactory;
import com.kma.summer2012.factory.HibernateUtil;
import com.kma.summer2012.factory.SpringBeansFactory;
import com.kma.summer2012.model.*;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import java.text.SimpleDateFormat;
import java.util.*;


public class MapViewFacadeImpl implements MapViewFacade {

    Integer getOurTime(Date d) {

        Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
        calendar.setTime(d);   // assigns calendar to given date
        return calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
    }

    Integer getDay(Date d) {

        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(d);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    Integer getMonth(Date d) {

        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(d);
        return calendar.get(Calendar.MONTH);
    }

    Integer getYear(Date d) {

        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(d);
        return calendar.get(Calendar.YEAR);
    }

    public Map<String, List<Integer>> sendMap(Date dateFromCal) throws Exception {
        DAOFactory factory = SpringBeansFactory.getInstance().getBeanByClass(DAOFactory.class);
        //CrumbsUserDAO crumbsUserDAO = (CrumbsUserDAO) factory.getCrumbsUserDAO();
        Session session = null;
        Map<String, List<Integer>> mapRequests = new TreeMap<String, List<Integer>>();
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            //Collection<Integer> users = crumbsUserDAO.getAllEngineers();
            List<CrumbsUser> users = session.createCriteria(CrumbsUser.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).add(Restrictions.eq("crumbsPosition", factory.getCrumbsPositionDAO().getById(3))).list();
            for (CrumbsUser user : users) {                                               //for each user
                List<Integer> listForDate = new ArrayList<Integer>();                                 //create List for date
                user.getCrumbsRequests().size();
                Set<CrumbsRequest> setOfRequests = user.getCrumbsRequests();                //and take his requests
                for (CrumbsRequest request : setOfRequests) {                               //from this set of requests --> take for each request
                    Hibernate.initialize(request);
                    Set<CrumbsDateAndTime> setOfDate = request.getCrumbsDateAndTimes();         //set of date and time
                    CrumbsRequestsState state = request.getCrumbsRequestsState();               //request state
                    int requestsId = request.getId();
                    for (CrumbsDateAndTime date : setOfDate) {                                  //and for each item from datatime set
                        Date dateBegin = date.getAssignedTimeBegin();                                //take only AssignedTimeBegin
                        Date dateEnd = date.getAssignedTimeEnd();                                   //and   AssignedTimeEnd
                        if (validateDate(dateBegin, dateEnd, dateFromCal))                          //if this date that we need
                            putInList(listForDate, getOurTime(dateBegin), getOurTime(dateEnd), state.getId(), requestsId);  // put them in map for this user
                    }
                }
                mapRequests.put(String.valueOf(user.getUserId() + "." + user.getSurnmNmSecondnm()), listForDate);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return mapRequests;
    }

    public List<Integer> putInList(List<Integer> listForDate, int timeBegin, int timeEnd, int requestState, int requestId) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(timeBegin);
        list.add(timeEnd);
        list.add(requestState);
        list.add(requestId);
        if (listForDate.size() == 0) {


            listForDate.addAll(list);
        } else {


            int position = 0;
            for (int i = 0; i < listForDate.size(); i += 4) {
                if (listForDate.get(i) < timeBegin) {
                    //listForDate.addAll(i, list);
                    //System.out.println(listForDate.size());
                    position = i;
                    break;
                } else if ((listForDate.size() - 4) == i) {
                    position = i + 4;
                    //System.out.println(listForDate.size());
                    // listForDate.addAll(list);
                    break;

                }

            }
            listForDate.addAll(position, list);
        }
        return listForDate;
    }

    public Boolean validateDate(Date dateBegin, Date dateEnd, Date dateFromCal) {
        return (((dateBegin != null) && (dateEnd != null)) && ((getYear(dateBegin).equals(getYear(dateFromCal))) && (getMonth(dateBegin).equals(getMonth(dateFromCal))) && (getDay(dateBegin).equals(getDay(dateFromCal)))));
    }

    @Override
    public Map<Integer, String> getRequestInfoMap(List<Integer> requestIdList) throws Exception {
        DAOFactory factory = SpringBeansFactory.getInstance().getBeanByClass(DAOFactory.class);
        List<CrumbsRequest> crumbsRequestList = new ArrayList<CrumbsRequest>();
        Map<Integer, String> requestInfoMap = new HashMap<Integer, String>();
        for (Integer requestId : requestIdList)
            crumbsRequestList.add(factory.getCrumbsRequestDAO().getById(requestId));
        for (CrumbsRequest crumbsRequest : crumbsRequestList) {
            String requestInfoString = "";
            int rumTimeAll = 0;
            String DATE_FORMAT = "yyyy/MM/dd HH:mm";
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
            for (CrumbsDateAndTime crumbsDateAndTime : crumbsRequest.getCrumbsDateAndTimes())
                requestInfoString += "Required date begin : " + sdf.format(crumbsDateAndTime.getDateBegin()) + ", Required date end : " + sdf.format(crumbsDateAndTime.getDateEnd());
            for (CrumbsRequestAndWork crumbsRequestAndWork : crumbsRequest.getCrumbsRequestAndWorks()) {
                int amountOfWork = crumbsRequestAndWork.getAmountOfWork();
                int rinTime = crumbsRequestAndWork.getCrumbsCatalogOfWork().getRuntime();
                rumTimeAll += amountOfWork * rinTime;

            }
            requestInfoString += " Runtime : " + rumTimeAll;
            requestInfoMap.put(crumbsRequest.getId(), requestInfoString);
        }
        return requestInfoMap;
    }
}




